<template>
	<view class="loginContainer">
		<!-- <image src="../../static/images/loginIcon.png" class="loginIcon"></image> -->

		<block>
			<!-- <view class="selectSchoolBox flex inputBox2" style="margin-top: 10px;">
				<picker mode="selector" :range="schoolList" @change="changeSelect" style="width: 100%;position: relative;">
					<view class="inputBox">{{schoolList[schoolIdx]}}</view>
					<image src="../../static/images/moreIcon3.png" @click="changeSelect" class="moreIcon3"></image>
				</picker>
			</view> -->
			<view class="uni-form-item uni-column flex inputBox2" style="margin-top: 10px;">
				<view class="title">账号：</view>
				<input class="uni-input inputVal" v-model="userNum" placeholder="请输入账号" />
			</view>
			<view class="uni-form-item uni-column flex inputBox2">
				<view class="title">密码：</view>
				<input class="uni-input inputVal" v-model="pwd" type="password" placeholder="请输入密码" />
			</view>
			<view class="uni-form-item uni-column flex inputBox2">
				<input class="uni-input inputVal1" type="text" v-model="imgCode" placeholder="请输入图形验证码" />
				<image :src="messageUrl" class="imgCodeUrl" @click="changeImgCode()"></image>
			</view>
			<!-- <view class="uni-form-item uni-column flex inputBox2">
				<input class="uni-input inputVal" style="width: 60%;" type="number" v-model="messageCode" placeholder="请输入短信验证码" />
				<button class="sendMessageBtn" v-if="!isSendMessage" @click="sendMessage()">获取验证码</button>
				<button class="sendMessageBtn" v-else>{{sendMessageTxt}}</button>
			</view> -->
			<button class="loginBtnBox" v-if="!openId" @click="h5Login()">登录</button>
			<button class="loginBtnBox" v-else @click="h5Bind()">绑定账号</button>
		</block>
		
		<block v-if="!openId">
			<view class="flex" style="justify-content:flex-end;">
				<view style="padding-right: 98rpx;color: red;" @click="register()" >新用户注册</view>
			</view>
		</block>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {},
				isShowPhone: false,
				schoolDataList: [],
				schoolList: ['请选择学校'],
				schoolIdx: 0,
				code: '',
				mobilePhone: '', //手机号码
				randomt: '', //时间戳随机数，获取图片用
				messageUrl: '', //图形验证码图片地址
				imgCode: '', //输入的图形验证码
				messageCode: '', //短信验证码
				isSendMessage: false, //判断是否发送验证码
				sendMessageTxt: '获取验证码', //发送验证码按钮展示文字
				timeWaitNum: 60,
				openId: '',
				userNum: '',
				pwd: '',
				tt: '',
				unionId: '',
				headPortrait: '',
				nickName: ''
			}
		},
		onShow(options) {
			//1、获取微信生成的code
			if(this.$utils.getUrlParam('code')) {
				this.code = this.$utils.getUrlParam('code');
				this.smallLogin();
			
			}else {
					const appid = getApp().globalData.appid;
					window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri=' + encodeURIComponent('https://t.acoer.cn/yuyueH5/#/pages/loginH5/loginH5') + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
			}
			
			this.changeImgCode()
		},
		onLoad() {
			// let code = this.getUrlCode('code')
		 //    console.log(code)
		 //    if(code !== null || code !== "") {
		 //        this.getOpenidAndUserinfo(code)
		 //    }	
		},
		methods: {
			// 获取code
			// 先判断url中有没有code，如果有code，表明已经授权，如果没有code，跳转微信授权链接
			getCode () {
				if(isWechat()) {
					// 截取地址中的code，如果没有code就去微信授权，如果已经获取到code了就直接把code传给后台获取openId
					let code = this.getUrlCode('code')
					if (code === null || code === '') {
						const appid = getApp().globalData.appid;
						window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri=' + encodeURIComponent('https://t.acoer.cn/yuyueH5/#/pages/loginH5/loginH5') + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
						// redirect_uri是授权成功后，跳转的url地址，微信会帮我们跳转到该链接，并且通过？的形式拼接code，这里需要用encodeURIComponent对链接进行处理。
						// 如果配置参数一一对应，那么此时已经通过回调地址刷新页面后，你就会再地址栏中看到code了。
						// http://127.0.0.1/pages/views/profile/login/login?code=001BWV4J1lRzz00H4J1J1vRE4J1BWV4q&state=1
					}
				}
			},
		   
			getUrlCode (name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\\+/g, '%20')) || null
			},
		   
			isWechat () {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			h5Bind() {
				//appId:wxab0c1228dea585c1
//AppSecret：dd50d51cefd8c439290628c10d2c74ed
				const appid = getApp().globalData.appid;
				let _this = this;
				const params = {
						channelId: getApp().globalData.channelId,
						appId: appid,
						mobilePhone: _this.userNum,
						imgCode: _this.imgCode,
						password: _this.pwd,
						t: _this.randomt,
						loginType: 1,
						nickName: _this.nickName,
						openId: _this.openId,
						unionId: _this.unionId,
						headPortrait: _this.headPortrait
					};
				
				uni.request({
					url: getApp().globalData.serverUrl + '/auth/auth/api/wxLoginBind',
					data: params,
					method: 'GET',
					success(res) {
						if (res.data.code == "10000") {
							getApp().globalData.token = res.data.data.token;
							uni.setStorage({
								key: 'token',
								data: res.data.data.token
							});
							uni.setStorage({
								key: 'userPhone',
								data: res.data.data.mobilePhone
							});
							getApp().globalData.userPhone = res.data.data.mobilePhone;
				
							// #ifdef MP-WEIXIN
							uni.reLaunch({
								url: '/pages/index/index'
							});
							// #endif
				
							// #ifdef H5
							// window.location.href = 'http://room.lib.hunnu.edu.cn/guoshiH5/index.html#/pages/index/index';
							// uni.reLaunch({
							// 	url: '/pages/index/index'
							// });
							window.location.href = 'https://t.acoer.cn/yuyueH5/index.html#/pages/index/index';
							// #endif	
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
							_this.changeImgCode()
						}
				
						/* if(getApp().globalData.orderNum && getApp().globalData.orderNum != '') {
							uni.redirectTo({
								url: '/pages/classroom/classroom?orderId='+getApp().globalData.orderNum 
							});
						}else {
							uni.switchTab({
								url: '/pages/index/index'
							});
						} */
					}
				})
			},
			searchSchoolList() {
				let _this = this;
				_this.$utils.requestFun('/base/base/api/queryChannelList?route=base', {}, 'GET').then(res => {
					console.log(res)
					let dataList = [];
					if (res.data.data && res.data.data.length > 0) {
						for (let i = 0; i < res.data.data.length; i++) {
							dataList.push(res.data.data[i].channelName);
						}
						_this.schoolDataList = res.data.data;
						_this.schoolList = _this.schoolList.concat(dataList);
					}
				});
			},
			//选择下拉框
			changeSelect(e) {
				this.schoolIdx = e.target.value;
			},
			//2、通过code获取用户信息
			smallLogin() {
				// if (this.schoolIdx == 0) {
				// 	uni.showToast({
				// 		title: "请选择学校！",
				// 		icon: 'none'
				// 	})
				// 	return false;
				// }
				let _this = this;
				// getApp().globalData.channelId = _this.schoolDataList[_this.schoolIdx - 1].channelId;
				uni.request({
					// 请求路径
					url: getApp().globalData.serverUrl + '/auth/auth/api/weChatLogin',
					// 请求参数code
					data: {
						channelId: getApp().globalData.channelId,
						appId: getApp().globalData.appid,
						code: _this.code
					},
					method: 'GET',
					success(res) {
						console.log(res)
						if(res.data.code === '10000') {
							getApp().globalData.token = res.data.data.token;
							uni.setStorage({
								key: 'token',
								data: res.data.data.token
							});
							
							//3、获取用户手机号码
							if (res.data.data.mobilePhone) {
								uni.setStorage({
									key: 'userPhone',
									data: res.data.data.mobilePhone
								});
								getApp().globalData.userPhone = res.data.data.mobilePhone;
								window.location.href = 'https://t.acoer.cn/yuyueH5/index.html#/pages/index/index';
								/* uni.reLaunch({
									url: '/pages/index/index'
								}); */
							} else {
								//3、获取用户手机号码
								_this.openId = res.data.data.openId;
								_this.unionId = res.data.data.unionId;
								_this.headPortrait = res.data.data.headPortrait;
								_this.nickName = res.data.data.nickName;
								_this.isShowPhone = true;
								_this.changeImgCode();
							}
						}
						else {
							if (res.data.code === '10008') {
								_this.openId = res.data.data.openId;
								_this.unionId = res.data.data.unionId;
								_this.headPortrait = res.data.data.headPortrait;
								_this.nickName = res.data.data.nickName;
								_this.isShowPhone = true;
								_this.changeImgCode();
							}
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					}
				});
			},
			//4、获取图形验证码
			changeImgCode() {
				this.randomt = new Date().getTime(); //时间戳随机数
				this.messageUrl = 'https://t.acoer.cn/auth/auth/api/authImage?route=auth&t=' + this.randomt; //图形验证码图片
			},
			verifityForm() {
				if (this.mobilePhone == '') {
					uni.showToast({
						title: "请输入手机号码！",
						icon: 'none'
					});
					return false;
				} else if (this.mobilePhone.length < 11) {
					uni.showToast({
						title: "请输入正确的手机号码！",
						icon: 'none'
					});
					return false;
				} else if (this.imgCode == '') {
					uni.showToast({
						title: "请输入图形验证码！",
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			verifityForm11() {
				// if(this.schoolIdx == 0) {
				// 	uni.showToast({
				// 		title: "请选择学校！",
				// 		icon: 'none'
				// 	})
				// 	return false;
				// }
				// let _this = this;
				// getApp().globalData.channelId = _this.schoolDataList[_this.schoolIdx-1].channelId;
				getApp().globalData.channelId = 'BJGYDX'
				if (this.userNum == '') {
					uni.showToast({
						title: "请输入账号！",
						icon: 'none'
					});
					return false;
				} else if (this.pwd == '') {
					uni.showToast({
						title: "请输入密码！",
						icon: 'none'
					});
					return false;
				} else if (this.imgCode == '') {
					uni.showToast({
						title: "请输入图形验证码！",
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			//5、发送短信验证码
			sendMessage() {
				let _this = this;
				if (this.verifityForm()) {
					uni.request({
						// 请求路径
						url: getApp().globalData.serverUrl + '/auth/auth/api/doSendSmsV2?route=auth',
						// 请求参数code
						data: {
							channelId: getApp().globalData.channelId,
							appId: getApp().globalData.appid,
							mobilePhone: _this.mobilePhone,
							terminalName: 'wx', //客户端名称 app端请固定填写app,微信端请固定填写wx
							imgCode: _this.imgCode, //	图片验证码
							t: _this.randomt //生成图片验证码时使用的密钥
						},
						method: 'GET',
						success(res) {
							if (res.data.code == "10000") {
								uni.showToast({
									title: "发送成功！",
									icon: 'none'
								})
								_this.calculateTime();
							} else {
								uni.showToast({
									title: res.data.msg ? res.data.msg : '系统繁忙，请稍后再试！',
									icon: 'none'
								});
							}
						}
					})
				}
			},
			//倒计时验证码
			calculateTime() {
				let _this = this;
				if (this.timeWaitNum == 0) {
					this.isSendMessage = false;
					this.sendMessageTxt = '获取验证码';
					this.timeWaitNum = 60;
					return;
				} else {
					this.isSendMessage = true;
					this.sendMessageTxt = this.timeWaitNum + 's后重试';
					this.timeWaitNum--;
				}
				setTimeout(() => {
					_this.calculateTime();
				}, 1000) //每1000毫秒执行一次
			},
			//6、真正注册登录
			h5Login() {
				let _this = this;
				if (this.verifityForm11()) {
					uni.request({
						url: getApp().globalData.serverUrl + '/auth/auth/api/memberLoginApi?route=auth',
						data: {
							channelId: getApp().globalData.channelId,
							appId: getApp().globalData.appid,
							mobilePhone: _this.userNum,
							imgCode: _this.imgCode,
							password: _this.pwd,
							t: _this.randomt,
							loginType: 1
						},
						method: 'GET',
						success(res) {
							if (res.data.code == "10000") {
								getApp().globalData.token = res.data.data.token;
								uni.setStorage({
									key: 'token',
									data: res.data.data.token
								});
								uni.setStorage({
									key: 'userPhone',
									data: res.data.data.mobilePhone
								});
								getApp().globalData.userPhone = res.data.data.mobilePhone;

								// #ifdef MP-WEIXIN
								uni.reLaunch({
									url: '/pages/index/index'
								});
								// #endif

								// #ifdef H5
								// window.location.href = 'http://room.lib.hunnu.edu.cn/guoshiH5/index.html#/pages/index/index';
								uni.reLaunch({
									url: '/pages/index/index'
								});
								// #endif	
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								})
								_this.changeImgCode()
							}

							/* if(getApp().globalData.orderNum && getApp().globalData.orderNum != '') {
								uni.redirectTo({
									url: '/pages/classroom/classroom?orderId='+getApp().globalData.orderNum 
								});
							}else {
								uni.switchTab({
									url: '/pages/index/index'
								});
							} */
						}
					})
				}
			},
			register() {
				// #ifdef H5
				// window.location.href = 'http://room.lib.hunnu.edu.cn/guoshiH5/index.html#/pages/index/index';
				uni.reLaunch({
					url: '/pages/register/register'
				});
				// #endif	
			}
		}
	}
</script>

<style>
	.loginContainer {
		width: 100%;
		height: 100vh;
		background: #FFFFFF;
		overflow: hidden;
	}

	.txtOverFlow {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.flex {
		display: flex;
	}

	.loginIcon {
		width: 369rpx;
		height: 369rpx;
		display: block;
		margin: 0 auto;
		margin-top: 31rpx;
	}

	.selectSchoolBox {
		width: 88%;
		height: 98rpx;
		line-height: 98rpx;
		margin: 80rpx 45rpx 45rpx 45rpx;
		/* background: #F6F6F6;
		border-radius: 49rpx; */
	}

	.inputBox {
		margin-left: 46rpx;
	}

	.moreIcon3 {
		width: 66rpx;
		height: 16rpx;
		position: absolute;
		right: 20px;
		top: 43%;
	}

	.loginBtnBox {
		width: 88%;
		height: 98rpx;
		line-height: 98rpx;
		margin: 80rpx 45rpx 45rpx 45rpx;
		background: linear-gradient(90deg, #19AD78, #1EBE85);
		border-radius: 49rpx;
		text-align: center;
		font-size: 32rpx;
		color: #FFFFFF;
	}

	.wxIcon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 13rpx;
		margin-top: 36rpx;
		margin-left: 34%;
	}

	.sendMessageBtn {
		width: 100px;
		height: 30px;
		line-height: 30px;
		text-align: center;
		color: #FFFFFF;
		font-size: 26rpx;
		background: linear-gradient(90deg, #19AD78, #1EBE85);
	}

	.inputBox2 {
		width: 85%;
		height: 30px;
		line-height: 30px;
		border: 1px solid #efefef;
		border-radius: 10px;
		margin: 0 auto;
		padding: 10px 0 10px 10px;
		margin-bottom: 10px;
	}

	.inputVal {
		margin-top: 4px;
		/* width: 85%; */
	}

	.inputVal1 {
		margin-top: 4px;
		width: 85%;
	}

	.imgCodeUrl {
		width: 242px;
		height: 30px;
		margin-right: 14px;
	}
</style>
